package edu.zzti.nlp.segment.nlpir;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import kevin.zhang.NLPIR;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import edu.zzti.nlp.model.NLPWord;

/**
 * Zhang HuaPing Segment and Pos tagger;
 * 
 * @author liuxiaoming
 * 
 */
public class NLPIRManager {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(NLPIRManager.class);

	// static NLPIR2011 NLPIR = new NLPIR2011();

	static NLPIR NLPIR = new NLPIR();

	String encoding = "UTF-8";

	static NLPIRManager manager;

	@SuppressWarnings("static-access")
	private NLPIRManager() {
		try {
			String argu = "./nlpir";
			if (NLPIR.NLPIR_Init(argu.getBytes(this.encoding), 1) == false) {
				logger.error("NLPIR JIN init failed!");
				// System.exit(-1);
				return;
			} else {
				logger.info("NLPIR JIN init successfully");
			}
			int nCount = NLPIR.NLPIR_ImportUserDict("userdict.txt".getBytes());
			logger.info("import user words " + nCount);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static NLPIRManager getInstance() {
		if (NLPIRManager.manager == null) {
			manager = new NLPIRManager();
		}
		return manager;
	}

	public String segment(String sentence) {
		String nativeStr = null;
		try {
			byte nativeBytes[] = NLPIR.NLPIR_ParagraphProcess(
					sentence.getBytes(encoding), 1);
			nativeStr = new String(nativeBytes, 0, nativeBytes.length - 1,
					encoding);
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage());
		}
		return nativeStr;
	}

	public List<NLPWord> segmentToNLPWord(String sentence) {
		String result = segment(sentence);
		List<NLPWord> words = new ArrayList<NLPWord>();
		String[] results = StringUtils.split(result, " ");
		for (int i = 0; i < results.length; i++) {
			NLPWord nlpWord = new NLPWord();
			nlpWord.setId(i);
			nlpWord.setText(StringUtils.substringBeforeLast(results[i], "/"));
			String pos = StringUtils.substringAfterLast(results[i], "/");
			nlpWord.setPos(pos);
			words.add(nlpWord);
		}
		return words;
	}

}
